import SwiftUI

struct FileItem: Identifiable {
    let id = UUID()
    let name: String
    let url: URL
    var isDirectory: Bool
}

struct FileBrowserView: View {
    @State private var showAlert = false
    @State private var alertMessage = ""
    @State private var files: [FileItem] = []
    @State private var currentDirectory: URL
    @State private var showingFileCreator = false
    @State private var showingFolderCreator = false
    @State private var showingFileEditor = false
    @State private var showingRenameSheet = false // 新增：重命名状态
    @State private var selectedFile: FileItem?
    @State private var fileContent = ""
    @State private var renameText = "" // 新增：重命名文本
    
    init(directory: URL? = nil) {
        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        _currentDirectory = State(initialValue: directory ?? documentsURL)
    }
    
    var body: some View {
        NavigationView {
            List {
                // 返回上级目录按钮
                if currentDirectory.path != FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.path {
                    Button(action: navigateUp) {
                        HStack {
                            Image(systemName: "arrow.up")
                                .font(.system(size: 16, weight: .medium))
                                .foregroundColor(.blue)
                            Text("返回上级目录")
                                .foregroundColor(.blue)
                        }
                    }
                }
                
                // 文件列表
                ForEach(files) { file in
                    if file.isDirectory {
                        NavigationLink(destination: FileBrowserView(directory: file.url)) {
                            FileRow(file: file, onRename: {
                                prepareRename(file: file) // 重命名回调
                            })
                        }
                    } else {
                        FileRow(file: file, onRename: {
                            prepareRename(file: file) // 重命名回调
                        })
                        .onTapGesture {
                            selectedFile = file
                            loadFileContent(file: file)
                            showingFileEditor = true
                        }
                    }
                }
                .onDelete(perform: deleteFile)
            }
            .listStyle(InsetGroupedListStyle())
            .navigationTitle(currentDirectory.lastPathComponent)
            .navigationBarItems(
                leading: Button(action: loadFiles) {
                    Image(systemName: "arrow.clockwise")
                        .font(.system(size: 18))
                },
                trailing: HStack(spacing: 16) {
                    // 文件夹创建按钮
                    Button(action: { showingFolderCreator = true }) {
                        Image(systemName: "folder.badge.plus")
                            .font(.system(size: 18))
                    }
                    
                    // 文件创建按钮
                    Button(action: { showingFileCreator = true }) {
                        Image(systemName: "doc.badge.plus")
                            .font(.system(size: 18))
                    }
                }
            )
            .sheet(isPresented: $showingFileCreator) {
                FileCreatorView(
                    title: "新建文件",
                    placeholder: "例如: notes.txt",
                    onCreate: createNewFile
                )
            }
            .sheet(isPresented: $showingFolderCreator) {
                FileCreatorView(
                    title: "新建文件夹",
                    placeholder: "输入文件夹名称",
                    onCreate: createNewFolder
                )
            }
            .sheet(isPresented: $showingRenameSheet) { // 新增：重命名弹窗
                if let file = selectedFile {
                    FileCreatorView(
                        title: "重命名\(file.isDirectory ? "文件夹" : "文件")",
                        placeholder: "新名称",
                        initialText: file.name, // 预填充当前名称
                        onCreate: { newName in
                            renameItem(file: file, newName: newName)
                        }
                    )
                }
            }
            .sheet(isPresented: $showingFileEditor) {
                if let file = selectedFile {
                    FileEditorView(
                        fileName: file.name,
                        content: $fileContent,
                        onSave: { newContent in
                            saveFileContent(file: file, content: newContent)
                        }
                    )
                }
            }
            .alert("提示", isPresented: $showAlert) {
                Button("确定", role: .cancel) { }
            } message: {
                Text(alertMessage)
            }
            .onAppear {
                loadFiles()
            }
        }
    }
    
    // MARK: - 文件操作函数
    
    // 返回上级目录
    func navigateUp() {
        currentDirectory.deleteLastPathComponent()
        loadFiles()
    }
    
    func loadFiles() {
        do {
            let contents = try FileManager.default.contentsOfDirectory(
                at: currentDirectory,
                includingPropertiesForKeys: [.isDirectoryKey],
                options: [.skipsHiddenFiles]
            )
            
            files = contents.map { url in
                let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory ?? false
                return FileItem(name: url.lastPathComponent, url: url, isDirectory: isDirectory)
            }.sorted {
                // 目录排在前面，然后按名称排序
                if $0.isDirectory && !$1.isDirectory { return true }
                if !$0.isDirectory && $1.isDirectory { return false }
                return $0.name.lowercased() < $1.name.lowercased()
            }
        } catch {
            alertMessage = "读取文件错误: \(error.localizedDescription)"
            showAlert = true
            files = []
        }
    }
    
    // 通用创建方法
    private func createItem(name: String, isDirectory: Bool) {
        guard !name.isEmpty else {
            alertMessage = "名称不能为空"
            showAlert = true
            return
        }
        
        let itemURL = currentDirectory.appendingPathComponent(name)
        
        guard !FileManager.default.fileExists(atPath: itemURL.path) else {
            alertMessage = "\(isDirectory ? "文件夹" : "文件")已存在"
            showAlert = true
            return
        }
        
        do {
            if isDirectory {
                try FileManager.default.createDirectory(at: itemURL, withIntermediateDirectories: true)
            } else {
                FileManager.default.createFile(atPath: itemURL.path, contents: nil, attributes: nil)
            }
            loadFiles()
        } catch {
            alertMessage = "创建\(isDirectory ? "文件夹" : "文件")失败: \(error.localizedDescription)"
            showAlert = true
        }
    }
    
    func createNewFile(name: String) {
        createItem(name: name, isDirectory: false)
    }
    
    // 创建文件夹
    func createNewFolder(name: String) {
        createItem(name: name, isDirectory: true)
    }
    
    // 新增：准备重命名
    func prepareRename(file: FileItem) {
        selectedFile = file
        showingRenameSheet = true
    }
    
    // 新增：重命名项目
    func renameItem(file: FileItem, newName: String) {
        guard !newName.isEmpty else {
            alertMessage = "名称不能为空"
            showAlert = true
            return
        }
        
        let newURL = currentDirectory.appendingPathComponent(newName)
        
        guard !FileManager.default.fileExists(atPath: newURL.path) else {
            alertMessage = "\(file.isDirectory ? "文件夹" : "文件")名称已存在"
            showAlert = true
            return
        }
        
        do {
            try FileManager.default.moveItem(at: file.url, to: newURL)
            loadFiles() // 刷新列表
        } catch {
            alertMessage = "重命名失败: \(error.localizedDescription)"
            showAlert = true
        }
    }
    
    func loadFileContent(file: FileItem) {
        do {
            let content = try String(contentsOf: file.url, encoding: .utf8)
            fileContent = content
        } catch {
            alertMessage = "读取文件内容错误: \(error.localizedDescription)"
            showAlert = true
            fileContent = ""
        }
    }
    
    func saveFileContent(file: FileItem, content: String) {
        do {
            try content.write(to: file.url, atomically: true, encoding: .utf8)
            showingFileEditor = false
        } catch {
            alertMessage = "保存文件错误: \(error.localizedDescription)"
            showAlert = true
        }
    }
    
    func deleteFile(at offsets: IndexSet) {
        for index in offsets {
            let file = files[index]
            do {
                try FileManager.default.removeItem(at: file.url)
                files.remove(at: index)
            } catch {
                alertMessage = "删除\(file.isDirectory ? "文件夹" : "文件")错误: \(error.localizedDescription)"
                showAlert = true
            }
        }
    }
}

// MARK: - 子视图
struct FileRow: View {
    let file: FileItem
    var onRename: () -> Void // 新增：重命名回调
    
    // 图标大小
    private var iconSize: CGFloat {
        file.isDirectory ? 22 : 20
    }
    
    var body: some View {
        HStack {
            Image(systemName: file.isDirectory ? "folder.fill" : "doc.text")
                .font(.system(size: iconSize, weight: .medium))
                .foregroundColor(file.isDirectory ? .orange : .blue)
                .frame(width: 24, height: 24)
                .padding(.trailing, 4)
            
            Text(file.name)
                .font(.system(size: 16))
            
            Spacer()
            
            if !file.isDirectory {
                Text("\(file.url.fileSizeString)")
                    .foregroundColor(.gray)
                    .font(.system(size: 12))
            }
        }
        .padding(.vertical, 8)
        .contentShape(Rectangle()) // 使整个行都可点击
        .contextMenu { // 新增：上下文菜单（长按/右键）
            Button {
                onRename() // 触发重命名
            } label: {
                Label("重命名", systemImage: "pencil")
            }
        }
    }
}

// 通用创建器视图
struct FileCreatorView: View {
    let title: String
    let placeholder: String
    let onCreate: (String) -> Void
    var initialText: String = "" // 新增：初始文本
    
    @State private var itemName = ""
    @Environment(\.presentationMode) var presentationMode
    
    // 新增：初始化方法支持初始文本
    init(title: String, placeholder: String, initialText: String = "", onCreate: @escaping (String) -> Void) {
        self.title = title
        self.placeholder = placeholder
        self._itemName = State(initialValue: initialText)
        self.onCreate = onCreate
    }
    
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text(title)) {
                    TextField(placeholder, text: $itemName)
                        .autocapitalization(.none)
                        .disableAutocorrection(true)
                }
            }
            .navigationTitle(title)
            .navigationBarItems(
                leading: Button("取消") {
                    presentationMode.wrappedValue.dismiss()
                },
                trailing: Button("确定") {
                    onCreate(itemName)
                    presentationMode.wrappedValue.dismiss()
                }
                    .disabled(itemName.isEmpty)
            )
        }
        .onAppear {
            // 自动选择所有文本
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                // 这里无法直接操作文本选择，但可以自动聚焦（需要额外实现）
            }
        }
    }
}

struct FileEditorView: View {
    let fileName: String
    @Binding var content: String
    let onSave: (String) -> Void
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        NavigationView {
            TextEditor(text: $content)
                .padding()
                .font(.system(.body, design: .monospaced))
                .navigationTitle(fileName)
                .navigationBarItems(
                    leading: Button("取消") {
                        presentationMode.wrappedValue.dismiss()
                    },
                    trailing: Button("保存") {
                        onSave(content)
                        presentationMode.wrappedValue.dismiss()
                    }
                )
        }
    }
}

// MARK: - 扩展
extension URL {
    var fileSizeString: String {
        do {
            let resources = try resourceValues(forKeys: [.fileSizeKey])
            let size = resources.fileSize ?? 0
            return ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file)
        } catch {
            return "未知大小"
        }
    }
}

struct FileBrowserView_Previews: PreviewProvider {
    static var previews: some View {
        FileBrowserView()
    }
}